import actionTypes from './constants';
import {Map} from 'immutable';
//定义一个初始状态
const isLogin = Boolean(window.localStorage.getItem('authToken')) || Boolean(window.sessionStorage.getItem('authToken'))
const adminInfo = JSON.parse(window.localStorage.getItem('adminInfo')) || JSON.parse(window.sessionStorage.getItem('adminInfo'));


const initState =Map({
    userMessage:{ 
        ...adminInfo, 
        isLogin:isLogin,
        isLoading: false
      }
    });

//进入页面获取token，如果有token，isLogin改为true

//导出一个方法
function reducer(state=initState, action) {
    switch(action.type){
        case actionTypes.START_LOGIN:
            return {
                ...state,
                isLoading:true
            }
        case actionTypes.LOAGIN_SUCCESS:
            // console.log(action.payLoad);
            // console.log("中级点");
            return {
                // ...state,
                // ...action.payLoad.adminInfo,
                // isLoading:false,
                // isLogin: true
                ...action.payLoad
            }
        case actionTypes.LOGIN_FAILED:
            //登录失败返回最初始的state
            const newState =  {
                admin_id: '',
                admin_name: '',
                admin_password: '',
                admin_avatar: '',
                admin_permission:'',
                isLogin: false,
                isLoading: false
            }
            return {
                ...state,
                ...newState
            }
        case actionTypes.CHANGEAVATAR:
            // console.log(action.payLoad.avatarUrl);
            return {
                ...state,
                avatar: action.payLoad.avatarUrl
            }
        case actionTypes.LOGOUT:
            return {
                ...state,
                isLogin: false
            }
        default:
            return state;
    }
}

export default reducer;